"""
主窗口UI
"""
from PyQt6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                              QPushButton, QLabel, QLineEdit, QListWidget, 
                              QGroupBox, QRadioButton, QMessageBox, QDialog,
                              QDialogButtonBox, QFormLayout, QCheckBox, QComboBox)
from PyQt6.QtCore import Qt, pyqtSignal, QSize
from PyQt6.QtGui import QFont, QIcon
import socket
from .icon_loader import load_app_icon


class QuitDialog(QDialog):
    """退出确认对话框"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("退出确认")
        self.setModal(True)
        self.setMinimumWidth(350)
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout()
        
        # 提示信息
        label = QLabel("您要执行什么操作？")
        label_font = QFont()
        label_font.setPointSize(11)
        label.setFont(label_font)
        layout.addWidget(label)
        
        # 选项按钮
        self.minimize_radio = QRadioButton("最小化到系统托盘（后台运行）")
        self.minimize_radio.setChecked(True)
        layout.addWidget(self.minimize_radio)
        
        self.quit_radio = QRadioButton("完全退出程序")
        layout.addWidget(self.quit_radio)
        
        # 记住选择
        self.remember_checkbox = QCheckBox("记住我的选择，下次不再询问")
        layout.addWidget(self.remember_checkbox)
        
        # 按钮
        button_layout = QHBoxLayout()
        ok_btn = QPushButton("确定")
        ok_btn.clicked.connect(self.accept)
        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(self.reject)
        
        button_layout.addStretch()
        button_layout.addWidget(ok_btn)
        button_layout.addWidget(cancel_btn)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def get_choice(self):
        """获取用户选择"""
        action = 'minimize' if self.minimize_radio.isChecked() else 'quit'
        remember = self.remember_checkbox.isChecked()
        return action, remember


class RoomDialog(QDialog):
    """房间创建/加入对话框"""
    
    def __init__(self, parent=None, mode="create"):
        super().__init__(parent)
        self.mode = mode
        self.setWindowTitle("创建房间" if mode == "create" else "加入房间")
        self.setModal(True)
        self.setMinimumWidth(400)
        self.init_ui()
    
    def init_ui(self):
        layout = QFormLayout()
        
        # 房间名称
        self.room_name_edit = QLineEdit()
        self.room_name_edit.setPlaceholderText("输入房间名称")
        layout.addRow("房间名称:", self.room_name_edit)
        
        # 如果是加入模式，需要输入房主IP
        if self.mode == "join":
            self.host_ip_edit = QLineEdit()
            self.host_ip_edit.setPlaceholderText("例如: 192.168.1.100")
            layout.addRow("房主IP:", self.host_ip_edit)
        
        # 按钮
        buttons = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | 
            QDialogButtonBox.StandardButton.Cancel
        )
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addRow(buttons)
        
        self.setLayout(layout)
    
    def get_room_info(self):
        """获取房间信息"""
        if self.mode == "create":
            return {
                "room_name": self.room_name_edit.text().strip()
            }
        else:
            return {
                "room_name": self.room_name_edit.text().strip(),
                "host_ip": self.host_ip_edit.text().strip()
            }


class SettingsDialog(QDialog):
    """设置对话框"""
    
    def __init__(self, parent=None, config=None):
        super().__init__(parent)
        self.config = config or {}
        self.setWindowTitle("设置")
        self.setModal(True)
        self.setMinimumWidth(450)
        self.init_ui()
    
    def init_ui(self):
        layout = QFormLayout()
        
        # 用户名
        self.username_edit = QLineEdit()
        self.username_edit.setText(self.config.get("user_name", ""))
        self.username_edit.setPlaceholderText("输入您的昵称")
        layout.addRow("用户名:", self.username_edit)
        
        # IP地址选择
        self.ip_combo = QComboBox()
        available_ips = self._get_all_lan_ips()
        
        if available_ips:
            self.ip_combo.addItems(available_ips)
            # 设置当前选择的IP
            current_ip = self.config.get("selected_ip", "")
            if current_ip and current_ip in available_ips:
                self.ip_combo.setCurrentText(current_ip)
            elif available_ips:
                self.ip_combo.setCurrentIndex(0)
        else:
            self.ip_combo.addItem("未检测到局域网IP")
        
        # 添加刷新按钮
        ip_layout = QHBoxLayout()
        refresh_btn = QPushButton("🔄 刷新")
        refresh_btn.setMaximumWidth(80)
        refresh_btn.clicked.connect(self._refresh_ips)
        ip_layout.addWidget(self.ip_combo, 1)
        ip_layout.addWidget(refresh_btn)
        ip_widget = QWidget()
        ip_widget.setLayout(ip_layout)
        layout.addRow("本机IP:", ip_widget)
        
        # 快捷键
        self.hotkey_edit = QLineEdit()
        self.hotkey_edit.setText(self.config.get("hotkey", "ctrl+alt+t"))
        self.hotkey_edit.setPlaceholderText("例如: ctrl+alt+t")
        layout.addRow("快捷键:", self.hotkey_edit)
        
        # 录音模式
        mode_layout = QHBoxLayout()
        self.ptt_radio = QRadioButton("按住录音（PTT）")
        self.toggle_radio = QRadioButton("切换录音（Toggle）")
        
        hotkey_mode = self.config.get("hotkey_mode", "ptt")
        if hotkey_mode == "toggle":
            self.toggle_radio.setChecked(True)
        else:
            self.ptt_radio.setChecked(True)
        
        mode_layout.addWidget(self.ptt_radio)
        mode_layout.addWidget(self.toggle_radio)
        mode_widget = QWidget()
        mode_widget.setLayout(mode_layout)
        layout.addRow("录音模式:", mode_widget)
        
        # 添加说明标签
        mode_desc = QLabel("按住模式：按住快捷键时录音，松开停止\n切换模式：按一下开始录音，再按一下停止")
        mode_desc.setStyleSheet("color: gray; font-size: 9pt;")
        mode_desc.setWordWrap(True)
        layout.addRow("", mode_desc)
        
        # 端口
        self.port_edit = QLineEdit()
        self.port_edit.setText(str(self.config.get("port", 9527)))
        self.port_edit.setPlaceholderText("默认: 9527")
        layout.addRow("通信端口:", self.port_edit)
        
        # 开机自启动
        self.auto_start_checkbox = QCheckBox("开机自动启动")
        self.auto_start_checkbox.setChecked(self.config.get("auto_start", False))
        layout.addRow("", self.auto_start_checkbox)
        
        # 开机启动时最小化
        self.start_minimized_checkbox = QCheckBox("开机启动时最小化到托盘")
        self.start_minimized_checkbox.setChecked(self.config.get("start_minimized", False))
        self.start_minimized_checkbox.setToolTip("勾选后，开机自动启动时不显示主窗口，直接最小化到系统托盘")
        layout.addRow("", self.start_minimized_checkbox)
        
        # 自动重连
        self.auto_rejoin_checkbox = QCheckBox("启动时自动加入上次房间")
        self.auto_rejoin_checkbox.setChecked(self.config.get("auto_rejoin", False))
        layout.addRow("", self.auto_rejoin_checkbox)
        
        # 按钮
        buttons = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | 
            QDialogButtonBox.StandardButton.Cancel
        )
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addRow(buttons)
        
        self.setLayout(layout)
    
    def _get_all_lan_ips(self):
        """获取所有局域网IP"""
        try:
            hostname = socket.gethostname()
            ip_list = socket.gethostbyname_ex(hostname)[2]
            
            # 过滤出局域网IP
            lan_ips = []
            for ip in ip_list:
                if ip.startswith('192.168.') or ip.startswith('10.') or ip.startswith('172.'):
                    lan_ips.append(ip)
            
            return lan_ips
        except Exception as e:
            print(f"获取IP列表失败: {e}")
            return []
    
    def _refresh_ips(self):
        """刷新IP列表"""
        self.ip_combo.clear()
        available_ips = self._get_all_lan_ips()
        
        if available_ips:
            self.ip_combo.addItems(available_ips)
        else:
            self.ip_combo.addItem("未检测到局域网IP")
    
    def get_settings(self):
        """获取设置"""
        try:
            port = int(self.port_edit.text().strip())
        except:
            port = 9527
        
        # 获取录音模式
        hotkey_mode = "toggle" if self.toggle_radio.isChecked() else "ptt"
        
        # 获取选择的IP
        selected_ip = self.ip_combo.currentText()
        if selected_ip == "未检测到局域网IP":
            selected_ip = ""
        
        return {
            "user_name": self.username_edit.text().strip(),
            "hotkey": self.hotkey_edit.text().strip(),
            "hotkey_mode": hotkey_mode,
            "selected_ip": selected_ip,
            "port": port,
            "auto_start": self.auto_start_checkbox.isChecked(),
            "start_minimized": self.start_minimized_checkbox.isChecked(),
            "auto_rejoin": self.auto_rejoin_checkbox.isChecked()
        }


class MainWindow(QMainWindow):
    """主窗口"""
    
    # 信号
    create_room_signal = pyqtSignal(str)  # 创建房间
    join_room_signal = pyqtSignal(str, str)  # 加入房间(房间名, 房主IP)
    leave_room_signal = pyqtSignal()  # 离开房间
    settings_changed_signal = pyqtSignal(dict)  # 设置更改
    
    def __init__(self, config_manager):
        super().__init__()
        self.config_manager = config_manager
        self.in_room = False
        self.init_ui()
    
    def init_ui(self):
        self.setWindowTitle("LAN 对讲机")
        self.setMinimumSize(600, 500)
        
        # 设置窗口图标
        self.setWindowIcon(load_app_icon())
        
        # 中央widget
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout()
        central_widget.setLayout(main_layout)
        
        # 标题
        title_label = QLabel("🎙️ LAN 对讲机")
        title_font = QFont()
        title_font.setPointSize(18)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        main_layout.addWidget(title_label)
        
        # 状态信息区域
        status_group = QGroupBox("状态信息")
        status_layout = QVBoxLayout()
        
        self.user_label = QLabel(f"👤 用户: {self.config_manager.get('user_name')}")
        self.ip_label = QLabel(f"📡 本机IP: {self.config_manager.get_local_ip()}")
        self.room_label = QLabel("🚪 房间: 未加入")
        self.hotkey_label = QLabel(f"⌨️ 快捷键: {self.config_manager.get('hotkey')}")
        
        status_layout.addWidget(self.user_label)
        status_layout.addWidget(self.ip_label)
        status_layout.addWidget(self.room_label)
        status_layout.addWidget(self.hotkey_label)
        
        status_group.setLayout(status_layout)
        main_layout.addWidget(status_group)
        
        # 成员列表
        members_group = QGroupBox("房间成员")
        members_layout = QVBoxLayout()
        
        self.members_list = QListWidget()
        members_layout.addWidget(self.members_list)
        
        members_group.setLayout(members_layout)
        main_layout.addWidget(members_group)
        
        # 按钮区域
        buttons_layout = QHBoxLayout()
        
        self.create_btn = QPushButton("创建房间")
        self.create_btn.clicked.connect(self.on_create_room)
        buttons_layout.addWidget(self.create_btn)
        
        self.join_btn = QPushButton("加入房间")
        self.join_btn.clicked.connect(self.on_join_room)
        buttons_layout.addWidget(self.join_btn)
        
        self.leave_btn = QPushButton("离开房间")
        self.leave_btn.clicked.connect(self.on_leave_room)
        self.leave_btn.setEnabled(False)
        buttons_layout.addWidget(self.leave_btn)
        
        main_layout.addLayout(buttons_layout)
        
        # 设置按钮
        settings_btn = QPushButton("⚙️ 设置")
        settings_btn.clicked.connect(self.on_settings)
        main_layout.addWidget(settings_btn)
        
        # 提示标签
        tip_label = QLabel(f"提示: 按下 {self.config_manager.get('hotkey')} 开始讲话")
        tip_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        tip_label.setStyleSheet("color: gray; font-style: italic;")
        main_layout.addWidget(tip_label)
    
    def on_create_room(self):
        """创建房间"""
        dialog = RoomDialog(self, mode="create")
        if dialog.exec() == QDialog.DialogCode.Accepted:
            info = dialog.get_room_info()
            room_name = info.get("room_name")
            if room_name:
                self.create_room_signal.emit(room_name)
            else:
                QMessageBox.warning(self, "错误", "请输入房间名称")
    
    def on_join_room(self):
        """加入房间"""
        dialog = RoomDialog(self, mode="join")
        if dialog.exec() == QDialog.DialogCode.Accepted:
            info = dialog.get_room_info()
            room_name = info.get("room_name")
            host_ip = info.get("host_ip")
            if room_name and host_ip:
                self.join_room_signal.emit(room_name, host_ip)
            else:
                QMessageBox.warning(self, "错误", "请输入房间名称和房主IP")
    
    def on_leave_room(self):
        """离开房间"""
        self.leave_room_signal.emit()
    
    def on_settings(self):
        """打开设置"""
        dialog = SettingsDialog(self, self.config_manager.config)
        if dialog.exec() == QDialog.DialogCode.Accepted:
            settings = dialog.get_settings()
            self.settings_changed_signal.emit(settings)
    
    def update_room_status(self, room_name: str, is_host: bool):
        """更新房间状态"""
        self.in_room = True
        role = "房主" if is_host else "成员"
        self.room_label.setText(f"🚪 房间: {room_name} ({role})")
        self.create_btn.setEnabled(False)
        self.join_btn.setEnabled(False)
        self.leave_btn.setEnabled(True)
    
    def update_left_room(self):
        """更新离开房间状态"""
        self.in_room = False
        self.room_label.setText("🚪 房间: 未加入")
        self.members_list.clear()
        self.create_btn.setEnabled(True)
        self.join_btn.setEnabled(True)
        self.leave_btn.setEnabled(False)
    
    def update_members(self, members):
        """更新成员列表"""
        self.members_list.clear()
        for member in members:
            self.members_list.addItem(f"👤 {member.name} ({member.ip})")
    
    def update_user_info(self, user_name: str, hotkey: str):
        """更新用户信息"""
        self.user_label.setText(f"👤 用户: {user_name}")
        self.hotkey_label.setText(f"⌨️ 快捷键: {hotkey}")
    
    def closeEvent(self, event):
        """关闭事件 - 询问用户是退出还是最小化"""
        from config.config_manager import ConfigManager
        
        # 获取配置
        config_manager = ConfigManager()
        close_to_tray = config_manager.get('close_to_tray', True)
        
        if close_to_tray is None or close_to_tray == True:
            # 显示对话框询问
            dialog = QuitDialog(self)
            result = dialog.exec()
            
            if result == QDialog.DialogCode.Accepted:
                # 获取用户选择
                action, remember = dialog.get_choice()
                
                if remember:
                    # 记住选择
                    config_manager.set('close_to_tray', action == 'minimize')
                
                if action == 'quit':
                    # 完全退出
                    event.accept()
                    # 通知主程序退出
                    from PyQt6.QtWidgets import QApplication
                    QApplication.quit()
                else:
                    # 最小化到托盘
                    event.ignore()
                    self.hide()
            else:
                # 用户取消
                event.ignore()
        elif close_to_tray:
            # 直接最小化到托盘
            event.ignore()
            self.hide()
        else:
            # 直接退出
            event.accept()
            from PyQt6.QtWidgets import QApplication
            QApplication.quit()

